package com.yj.suncity.activity.shouye;

import java.util.List;

import org.json.JSONObject;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.yj.suncity.R;
import com.yj.suncity.activity.shouye.CityHelpListActivity.CityHelpAdapter;
import com.yj.suncity.activity.shouye.CityHelpListActivity.ViewHolder;
import com.yj.suncity.async.AsyncTaskUtil;
import com.yj.suncity.async.ThreadUtils;
import com.yj.suncity.async.AsyncTaskUtil.ResultCallBack;
import com.yj.suncity.async.ThreadUtils.OnResultListener;
import com.yj.suncity.bean.CityHelpBean;
import com.yj.suncity.bean.CityHelpListBean;
import com.yj.suncity.constant.ShareCon;
import com.yj.suncity.constant.URLCon;
import com.yj.suncity.user.LoginActivity;
import com.yj.suncity.utis.CircleImageView;
import com.yj.suncity.utis.PullToRefreshView;
import com.yj.suncity.utis.SharedPreferencesUtil;
import com.yj.suncity.utis.ToastUtil;
import com.yj.suncity.utis.Utils;
import com.yj.suncity.utis.PullToRefreshView.OnFooterRefreshListener;
import com.yj.suncity.utis.PullToRefreshView.OnHeaderRefreshListener;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class CityHelpCommentActivity extends Activity implements
		OnHeaderRefreshListener, OnFooterRefreshListener {

	private Context context;
	private String helpId;
	private boolean mRefreshHeadFlag = true;// 判断是否刷新的是头部(刚开始默认是头部刷新)
	private boolean mRefreshFlag = false;// 判断是否刷新
	private PullToRefreshView mPullToRefreshView = null;
	private int pageNum = 1;
	private ListView mList_city_comment;
	private CommentAdapter adapter;
	private List<CityHelpBean> detailInfos;
	private DisplayImageOptions options;
	private ImageLoader imageLoader;
	private SharedPreferencesUtil preferencesUtil = SharedPreferencesUtil
			.getInstance();
	private boolean isLogin;
	private boolean isCollect;
	private ImageView mImag_collect_normal, mImag_collect_press;
	private String userId;

	CircleImageView mImg_head;
	TextView mTxt_release_username;
	TextView mTxt_release_time;
	TextView mTxt_gave_num;
	TextView mTxt_help_content;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_city_help_comment);
		context = this;
		helpId = getIntent().getStringExtra("helpid");
		imageLoader=ImageLoader.getInstance();
		options = new DisplayImageOptions.Builder()
				.showStubImage(R.drawable.android_layout_detail)
				.showImageForEmptyUri(R.drawable.android_layout_detail)
				.showImageOnFail(R.drawable.android_layout_detail)
				.cacheInMemory(true).cacheOnDisc(true)
				// .displayer(new RoundedBitmapDisplayer(10))// 设置成圆角图片
				.bitmapConfig(Bitmap.Config.RGB_565) // 设置图片的解码类型
				.build();
		findView();
		initData(1);

		// intent.putExtra("datetime", helpBean.getRelease_datetime());
		// intent.putExtra("username", helpBean.getRelease_username());
		// intent.putExtra("give_num", helpBean.getGive_num());
		// intent.putExtra("help_content", helpBean.getHelp_content());
		// intent.putExtra("head_photo", helpBean.getHead_photo());

	}

	@Override
	protected void onResume() {
		isLogin = preferencesUtil.getBoolean(context, ShareCon.USERFILE,
				ShareCon.ISLOGIN, false);
		if (isLogin) {
			userId = preferencesUtil.getString(context, ShareCon.USERFILE,
					ShareCon.USERID, "");
			getCollectStatus();
		}
		super.onResume();
	}

	private void findView() {

		mImg_head = (CircleImageView) findViewById(R.id.img_head);
		mTxt_release_username = (TextView) findViewById(R.id.txt_release_username);
		mTxt_release_time = (TextView) findViewById(R.id.txt_release_time);
		mTxt_gave_num = (TextView) findViewById(R.id.txt_give_num);
		mTxt_help_content = (TextView) findViewById(R.id.txt_help_content);

		mTxt_release_username.setText(getIntent().getStringExtra("username"));
		mTxt_release_time.setText(""
				+ Utils.DateFormatDate(getIntent().getStringExtra("datetime")));
		mTxt_gave_num.setText(getIntent().getStringExtra("give_num")+"元");
		if (getIntent().getStringExtra("give_num").equals("")) {
			findViewById(R.id.lay_linear_shang).setVisibility(View.GONE);
		}
		mTxt_help_content.setText(getIntent().getStringExtra("help_content"));
		imageLoader.displayImage(
				URLCon.HOST + getIntent().getStringExtra("head_photo"),
				mImg_head, options);

		mImag_collect_normal = (ImageView) findViewById(R.id.img_collet_normal);
		mImag_collect_press = (ImageView) findViewById(R.id.img_collet_press);
		mPullToRefreshView = (PullToRefreshView) findViewById(R.id.main_pull_refresh_view);
		mPullToRefreshView.setOnHeaderRefreshListener(this);
		mPullToRefreshView.setOnFooterRefreshListener(this);
		mList_city_comment = (ListView) findViewById(R.id.list_view_comment);

	}

	private void initData(int index) {
		String path = URLCon.同城帮帮 + "?action=cityhelpcommentdetail&"
				+ "pagesize=20&pageindex=" + index + "&id=" + helpId;
		Log.d("", path);
		AsyncTaskUtil asyncTaskUtil = new AsyncTaskUtil(context, null,
				mPullToRefreshView, mRefreshFlag, null, true, "正在加载......",
				new AsyncTaskUtil.ResultCallBack() {
					@Override
					public void JSONResult(JSONObject jsonObject) {
						CityHelpListBean listBean = new CityHelpListBean(
								jsonObject);
						pageNum = Integer.valueOf(listBean.getTotalpage());
						if (mRefreshHeadFlag) {
							adapter = null;
						}
						if (adapter == null) {
							detailInfos = listBean.getData();
							adapter = new CommentAdapter(detailInfos);
							mList_city_comment.setAdapter(adapter);
						} else {
							detailInfos.addAll(listBean.getData());
							adapter.notifyDataSetChanged();
						}
					}
				});
		asyncTaskUtil.execute(path);
	}

	class CommentAdapter extends BaseAdapter {
		private List<CityHelpBean> helpBeans;

		public CommentAdapter(List<CityHelpBean> helpBeans) {
			super();
			this.helpBeans = helpBeans;
		}

		@Override
		public int getCount() {
			return helpBeans.size();
		}

		@Override
		public Object getItem(int position) {
			return helpBeans.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = LayoutInflater.from(context).inflate(
						R.layout.adapter_city_help_comment, null);

				holder.mImg_head = (CircleImageView) convertView
						.findViewById(R.id.img_head);
				holder.mTxt_comment_username = (TextView) convertView
						.findViewById(R.id.txt_comment_username);
				holder.mTxt_comment_time = (TextView) convertView
						.findViewById(R.id.txt_comment_time);
				holder.mTxt_comment_content = (TextView) convertView
						.findViewById(R.id.txt_comment_content);

				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			CityHelpBean helpBean = helpBeans.get(position);
			holder.mTxt_comment_username
					.setText(helpBean.getComment_username());
			holder.mTxt_comment_time.setText(""
					+ Utils.DateFormatDate(helpBean.getComment_datetime()));
			holder.mTxt_comment_content.setText(helpBean
					.getComment_usercontent());
			if (!helpBean.getComment_userphoto().equals("")) {
				imageLoader.displayImage(
						URLCon.HOST + helpBean.getComment_userphoto(),
						holder.mImg_head, options);
			} else {
				holder.mImg_head
						.setImageResource(R.drawable.android_layout_detail);
			}
			return convertView;
		}
	}

	class ViewHolder {
		CircleImageView mImg_head;
		TextView mTxt_comment_username;
		TextView mTxt_comment_time;
		TextView mTxt_comment_content;
	}

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnHeadBack:
			this.finish();
			break;
		case R.id.btn_comment:
			if (isLogin) {
				Intent intent = new Intent(this,
						CityHelpSubmitCommentActivity.class);
				intent.putExtra("userid", userId);
				intent.putExtra("helpid", helpId);
				startActivityForResult(intent, 1);

			} else {
				startActivity(new Intent(this, LoginActivity.class));
			}
			break;
		case R.id.lay_rela_collect:// 添加/移除收藏
			if (!isLogin) {
				startActivity(new Intent(this, LoginActivity.class));
				return;
			}
			if (isCollect) {
				removeCollect();
			} else {
				addCollect();
			}
			break;
		}
	}

	private void addCollect() {
		String path = URLCon.收藏 + "?action=addcollection&userid=" + userId
				+ "&id=" + helpId + "&type=4";
		Log.d("", "添加收藏：" + path);
		AsyncTaskUtil asyncTaskUtil = new AsyncTaskUtil(context, null, null,
				false, null, true, "添加收藏......", new ResultCallBack() {
					@Override
					public void JSONResult(JSONObject jsonObject) {
						if (jsonObject.optString("success").equals("1")) {
							isCollect = true;
							mImag_collect_normal.setVisibility(View.GONE);
							mImag_collect_press.setVisibility(View.VISIBLE);
							ToastUtil.ShowToast(context, "收藏成功！");
						} else {
							ToastUtil.ShowToast(context,
									"" + jsonObject.optString("msg"));
						}
					}
				});
		asyncTaskUtil.execute(path);
	}

	private void getCollectStatus() {
		String path = URLCon.收藏 + "?action=getcollectionstate&userid=" + userId
				+ "&id=" + helpId + "&type=4";

		Log.d("", "获取收藏：" + path);
		ThreadUtils threadUtils = new ThreadUtils();
		threadUtils.startThread(path, new OnResultListener() {
			@Override
			public void jsonResult(JSONObject json) {
				if (json.optString("success").equals("1")) {
					if (json.optString("state").equals("1")) {
						isCollect = true;
						mImag_collect_normal.setVisibility(View.GONE);
						mImag_collect_press.setVisibility(View.VISIBLE);
					} else {
						isCollect = false;
						mImag_collect_normal.setVisibility(View.VISIBLE);
						mImag_collect_press.setVisibility(View.GONE);
					}
				}
			}
		});
	}

	private void removeCollect() {
		String path = URLCon.收藏 + "?action=delcollection&userid=" + userId
				+ "&id=" + helpId + "&type=4";
		Log.d("", "添加收藏：" + path);
		AsyncTaskUtil asyncTaskUtil = new AsyncTaskUtil(context, null, null,
				false, null, true, "删除收藏......", new ResultCallBack() {
					@Override
					public void JSONResult(JSONObject jsonObject) {
						if (jsonObject.optString("success").equals("1")) {
							isCollect = false;
							setResult(1);
							mImag_collect_normal.setVisibility(View.VISIBLE);
							mImag_collect_press.setVisibility(View.GONE);
							ToastUtil.ShowToast(context, "删除收藏成功！");
						} else {
							ToastUtil.ShowToast(context,
									"" + jsonObject.optString("msg"));
						}
					}
				});
		asyncTaskUtil.execute(path);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == 1 && resultCode == 1) {
			mRefreshHeadFlag = true;// 判断是否刷新的是头部(刚开始默认是头部刷新)
			mRefreshFlag = false;// 判断是否刷新
			indexPage = 1;
			initData(1);
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public void onFooterRefresh(PullToRefreshView view) {
		mPullToRefreshView.postDelayed(new Runnable() {
			@Override
			public void run() {
				mRefreshHeadFlag = false;
				mRefreshFlag = true;

				++indexPage;
				if (indexPage > pageNum) {
					ToastUtil.ShowToast(context, "没有更多数据！");
					mPullToRefreshView.onFooterRefreshComplete();
					return;
				} else {
					initData(indexPage);
				}

				// mPullToRefreshView.onFooterRefreshComplete();
			}
		}, 1);

	}

	int indexPage = 1;

	@Override
	public void onHeaderRefresh(PullToRefreshView view) {
		mPullToRefreshView.postDelayed(new Runnable() {
			@Override
			public void run() {
				mRefreshHeadFlag = true;
				mRefreshFlag = true;
				// if (async != null) {
				// Utils.cancelTaskInterrupt(async);
				// async = null;
				// }
				indexPage = 1;// 刷新头部时将页数初始化为1
				initData(indexPage);
				// mPullToRefreshView.onHeaderRefreshComplete();
			}
		}, 1);
	}

}
